package cn.tedu.ivos.vehicle.service.impl;


import cn.tedu.ivos.base.exception.ServiceException;
import cn.tedu.ivos.base.response.StatusCode;
import cn.tedu.ivos.vehicle.mapper.VehicleMapper;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleQuery;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleSaveParam;
import cn.tedu.ivos.vehicle.pojo.entity.Vehicle;
import cn.tedu.ivos.vehicle.pojo.vo.VehicleVO;
import cn.tedu.ivos.vehicle.service.VehicleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class VehicleServiceImpl implements VehicleService {

    @Autowired
    VehicleMapper vehicleMapper;

    @Override
    public List<VehicleVO> selectVehicle(VehicleQuery vehicleQuery) {
        List<VehicleVO> list = vehicleMapper.selectVehicle(vehicleQuery);
        return list;
    }

    @Override
    public void saveVehicle(VehicleSaveParam vehicleSaveParam) {
        Vehicle vehicle = new Vehicle();
        BeanUtils.copyProperties(vehicleSaveParam, vehicle);
        if (vehicle.getId() == null) {
            if (vehicleMapper.selectVehicleByLicense(vehicle.getLicense()) != null) {
                throw new ServiceException(StatusCode.OPERATION_FAILED);
            }
            vehicle.setCreateTime(new Date());
            vehicle.setStatus("1");
            vehicleMapper.insert(vehicle);
        } else {
            vehicle.setUpdateTime(new Date());
            vehicleMapper.update(vehicle);
        }
    }
    @Override
    public void deleteVehicle(Long vehicleId) {
        vehicleMapper.deleteVehicle(vehicleId);
    }

    @Override
    public void unbindVehicle(Long vehicleId) {
        Vehicle vehicle = new Vehicle();
        vehicle.setId(vehicleId);
        vehicle.setGeofenceBindStatus("0");
        vehicle.setGeofenceId(null);
        vehicle.setUpdateTime(new Date());
        //之前的update方法有 if test !=null,要求是如果值为null则不更新
        //但是现在的业务更新的值就是null值,需要给当前车辆的geofence_id设为null
        //所以需要单独设置一个mapper层的方法,给当前车辆的geofence_id设为null
        vehicleMapper.updateNullValue(vehicle);
    }
    @Override
    public void bindVehicle(Long geofenceId, Long vehicleId) {
        Vehicle vehicle = new Vehicle();
        vehicle.setId(vehicleId);
        vehicle.setGeofenceId(geofenceId);
        vehicle.setGeofenceBindStatus("1");
        vehicle.setUpdateTime(new Date());
        vehicleMapper.update(vehicle);
    }
}
